#include <dht.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>

HTTPClient http;
String GetUrl;
String response;


dht DHT;
#define DHT11_PIN D2
float Temp, Humi;
String Get_Time = "";

// Update these with values suitable for your network.
const char* ssid = "602iot";
const char* password = "18wulian";
const char* mqtt_server = "192.144.231.242";

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[200];
int value = 0;

DynamicJsonDocument doc(512);

void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  // 连接苏宁网站的授时网页
  GetUrl = "http://quan.suning.com/getSysTime.do";
  http.setTimeout(5000);
  http.begin(GetUrl);
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  long now = millis();
  if (now - lastMsg > 2000) {
    Get_Temp_Humi();
    lastMsg = now;
    ++value;
    // 从网站获得网页内容
    int httpCode = http.GET();
    if (httpCode > 0) {
      Serial.printf("[HTTP] GET... code: %d\n", httpCode);
      if (httpCode == HTTP_CODE_OK) {
        //读取响应内容
        response = http.getString();
        // 将response替换成你想处理的字符串
        deserializeJson(doc, response);
        JsonObject obj = doc.as<JsonObject>();
        String Time = obj["sysTime2"];
        Get_Time = Time;
        Serial.print("sysTime2: ");
        Serial.println(Time);
      }
    } else {
      Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
    }
    http.end();
    delay(3000);
    snprintf (msg, 200, "{\"Temperature\": \"%.2f\", \"Humidity\": \"%.2f\", \"ts\": \"%s\"}", Temp, Humi, Get_Time.c_str());
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish("testtopic/0", msg);
  }
}

void Get_Temp_Humi() {
  int chk = DHT.read11(DHT11_PIN);
  switch (chk)
  {
    case DHTLIB_OK:
      Serial.print("OK\t");
      break;
    case DHTLIB_ERROR_CHECKSUM:
      Serial.print("Checksum error\t");
      break;
    case DHTLIB_ERROR_TIMEOUT:
      Serial.print("Time out error\t");
      break;
    default:
      Serial.print("Unknown error\t");
      break;
  }
  // DISPLAY DATA
  Temp = DHT.temperature;
  Humi = DHT.humidity;
  Serial.print("Humidity:");
  Serial.print(Humi, 1);
  Serial.print("\tTemperature:");
  Serial.println(Temp, 1);
}